/*
Copyright 2010 Bryce Alcock

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.com

 */
package com.ecocrypt.network.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 *  This class will determine the size of a serializable object by serializing it out to a byte[],
 * and then looking at the length of the byte[].  This will be very slow for large objects,
 * and should only be used for sampling purposes.
 */
public class SizeOfUtil {

    /** Creates a new instance of SizeOfUtil */
    public SizeOfUtil() {
    }

    /**
     * This method will determine the number of bytes in an object by serializing the
     * object to a byte[] and calculating the length of the byte[].
     * @param serializable the serializable object of which the size is desired.
     * @return then number of bytes in this object.
     */

    public static long sizeof(Serializable s) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(s);
            return baos.toByteArray().length;
        } catch (IOException ex) {
            System.err.println("Exception getting the size of: " + s.getClass().getName());
            ex.printStackTrace(System.out);
        }
        return 0;
    }
}
